package com.rtsapp.server.network.protocol.telnet;

import com.rtsapp.server.logger.format.StackTrace;
import com.rtsapp.server.network.protocol.ProtocolInHandler;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import com.rtsapp.server.logger.Logger;

import java.net.InetAddress;
import java.util.Date;

/**
 * Handles a server-side channel.
 */
@Sharable
public class TelnetServerHandler extends ProtocolInHandler {

    private static final Logger LOGGER =com.rtsapp.server.logger.LoggerFactory.getLogger( TelnetServerHandler.class );
	

    @Override
    public void channelRead( ChannelHandlerContext ctx, Object msg ) throws Exception {
    	
    	try{
    		String request = (String)msg;
	    	processMessage( ctx,  request );
    	}catch( Throwable ex ) {
            LOGGER.error("processMessage error", ex);
            String error = StackTrace.getStackTrace(ex);
            writeResponse(ctx, "操作出错:" + error, false  );
        }

    }
    
    
    public void processMessage( ChannelHandlerContext ctx,   String request ){
    	
    	   String response;
           boolean close = false;
           if (request.isEmpty()) {
               response = "Please type something.\r\n";
           } else if ("bye".equals(request.toLowerCase())) {
               response = "Have a good day!\r\n";
               close = true;
           } else {
               response = "Did you say '" + request + "'?\r\n";
           }
           
           writeResponse( ctx, response, close );
    }
    
    
    protected void writeResponse( ChannelHandlerContext ctx, String response, boolean close ) {

        // We do not need to write a ChannelBuffer here.
        // We know the encoder inserted at TelnetPipelineFactory will do the conversion.
        ChannelFuture future = ctx.write(response);

        // Close the connection after sending 'Have a good day!'
        // if the client has sent 'bye'.
        if (close) {
            future.addListener(ChannelFutureListener.CLOSE);
        }	
        
    }
    
    
    
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        LOGGER.error( "TelnetServerHandler exceptionCaught" , cause );
        ctx.close();
    }
}
